﻿using System;
using System.Threading.Tasks;
using RestSharp;
using RestSharp.Authenticators;

namespace ATSSDK.Internal;

internal class CustomJwtAuthenticator(string clientId, string clientPassword) : IAuthenticator
{
    private JwtResponse? _jwtResponse = null;
    private DateTime _lastTokenTime;

    public async ValueTask Authenticate(IRestClient client, RestRequest request)
    {
        if (_jwtResponse is null || DateTime.Now - _lastTokenTime > TimeSpan.FromSeconds(_jwtResponse.expires_in - 60))
        {
            await GetToken(client.Options.BaseUrl!);
        }
        var parameter = new HeaderParameter(KnownHeaders.Authorization, $"{_jwtResponse!.token_type} {_jwtResponse.access_token}");
        request.AddOrUpdateParameter(parameter);
    }

    private async ValueTask GetToken(Uri baseUri)
    {
        var tokenRequest = new RestRequest("api/token/client", Method.Post);
        tokenRequest.AddJsonBody(new { clientId, clientPassword });
        using var tokenClient = new RestClient(baseUri);
        var apiRes = await tokenClient.PostAsync<ApiResponse<JwtResponse>>(tokenRequest);
        _jwtResponse = apiRes?.Result;
        if (_jwtResponse is null || string.IsNullOrEmpty(_jwtResponse.access_token))
        {
            throw new ATSException("Failed to get JWT token");
        }
        _lastTokenTime = DateTime.Now;
    }
}
